package com.chookss.video

import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.Point
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import android.widget.ExpandableListView
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatDialog
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProviders
import com.chookss.MyApp
import com.chookss.R
import com.chookss.base.StaticClass
import com.chookss.tools.httpForm
import com.chookss.tools.Utils
import com.chookss.video.entity.VideoComment
import com.chookss.video.entity.VideoEntity
import com.chookss.video.model.VideoModel
import com.chookss.video.response.VideoCommentsListResponse
import com.johnrambo.ktea.ktExtends.ShareUtils
import errorToast
import kotlinx.android.synthetic.main.item_load_more.view.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashMap

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2021/1/21 18:43
 * Note:
 */
class VideoCommentsDialog(context: Context,var video: VideoEntity): AppCompatDialog(context, R.style.DialogFullWidthDimNotEnabled) {

    val mRootView:View
    val mListView: ExpandableListView
    var listener: DialogInterface.OnClickListener? = null
    var listener2: DialogInterface.OnClickListener? = null
    fun changeComment(data:String, listener: DialogInterface.OnClickListener?): VideoCommentsDialog? {
        this.listener2 = listener
        return this
    }
    val tvTitle:TextView
    private val footerView by lazy {
        LayoutInflater.from(context).inflate(R.layout.item_load_more, null)
    }

    init {
        mRootView = View.inflate(context, R.layout.dialog_video_comments, null)
        mRootView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            (screenSizeInPixel(context).y * 0.75f).toInt())
        tvTitle = mRootView.findViewById(R.id.tvTitle)
        mListView = mRootView.findViewById(R.id.listView)
        mListView.setGroupIndicator(null)
        mListView.setOnGroupClickListener { parent, v, groupPosition, id ->
            true
        }
        mRootView.findViewById<ImageView>(R.id.ivClose).setOnClickListener { dismiss() }
        mRootView.findViewById<View>(R.id.inputBar).setOnClickListener {
            showReplyVideoDialog()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mRootView)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        window?.setGravity(Gravity.BOTTOM)
        window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
        window?.setWindowAnimations(R.style.DialogBottomAnim)
        //以下两行如果不添加, dialog将会随着输入法出现被顶起
        window?.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window?.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)

        mListView.addFooterView (footerView, null, false)
        mListView.setAdapter(adapter)
        mListView.setOnGroupClickListener { parent, v, groupPosition, id ->
            showReplyCommentDialog(adapter.getGroup(groupPosition), null)
            true
        }
        mListView.setOnChildClickListener { parent, v, groupPosition, childPosition, id ->
            if (adapter.getChildType(groupPosition, childPosition) == VideoCommentsAdapter.ChildTypePlaceHolder) {
                clickOnChildPlaceholder(groupPosition)
            } else {
                var groupItem = adapter.getGroup(groupPosition)
                showReplyCommentDialog(groupItem, groupItem.children[childPosition])
            }
            true
        }
        loadMoreData()
        adapter.onItemBtnClick = object : VideoCommentsAdapter.OnItemBtnClick {
            override fun onCommentClick(view: View, comment: VideoComment) {
                likeComment(view, comment)
            }
        }
    }

    private fun likeComment(v: View, entity: VideoComment) {
        var isLike = !v.isSelected
        viewModel.likeComment(entity.commentCode,entity.videoComment, isLike, {
            var numInt:Int=0
            if(!Utils.isNull(entity.commentLikeCounts)){
                numInt= entity.commentLikeCounts.toInt()
            }
            numInt+=if (isLike) 1 else -1
            entity.commentLikeCounts=numInt.toString()
            entity.isLike = if (isLike) "1" else "0"
            if (v.tag != null && v.tag is VideoComment) {
                var e1 = v.tag as VideoComment
                if (e1.commentCode == entity.commentCode) {
                    (v as TextView).text = entity.commentLikeCounts.toString()
                    v.isSelected = isLike
                }
            }
        }, {
        })
    }

    private fun clickOnChildPlaceholder(groupPosition:Int) {
        var groupItem = adapter.getGroup(groupPosition)
        var state = adapter.groupStateOf(groupItem)
        if (state.clickToLoad && adapter.isLoadingGroupId == null) {
            adapter.isLoadingGroupId = groupItem.comment.commentCode
            adapter.notifyDataSetChanged()
            loadChildComments(groupItem)
        }
        if (state == VideoCommentsAdapter.GroupState.AtEnd) {
            groupItem.showChildren = false
            adapter.notifyDataSetChanged()
        } else if (state == VideoCommentsAdapter.GroupState.AtBegin) {
            groupItem.showChildren = true
            adapter.notifyDataSetChanged()
        }
    }

    private fun showReplyVideoDialog() {
        var dialog = VideoCommentsInputDialog(context,"1")
        dialog.inputAction = { text ->
            viewModel.commentVideo(video, text, { commentId ->
                var comment = createLocalComment(commentId, text)
                var groupItem = VideoCommentsAdapter.GroupItem(comment)
                adapter.groups.add(0, groupItem)
                adapter.notifyDataSetChanged()
                for (i in 0 until adapter.groupCount) {
                    mListView.expandGroup(i)
                }
                mListView.setSelectedGroup(0);
                tvTitle.text = "${adapter.groups.size}条评论"
                if (listener2 != null) {
                    listener2!!.onClick(this, 1)
                }
                if(adapter.groups.size==0){
                    initFooter("暂无评论", null)
                }else{
                    initFooter("已显示全部评论", null)
                }
            }, {
                context.errorToast(it)
            })
        }
        dialog.show()
        dialog.editText?.hint = "评论"
    }

    private fun showReplyCommentDialog(group:VideoCommentsAdapter.GroupItem, comment:VideoComment?) {
        var dialog = VideoCommentsInputDialog(context,"1")
        println(group?.comment?.fromEmployeeCode)
        println(group?.comment?.toEmployeeCode)
        println(group?.comment?.lvlNo)
        println(comment?.fromEmployeeCode)
        println(comment?.toEmployeeCode)
        println(comment?.lvlNo)
        dialog.inputAction = { text ->
            viewModel.commentComment(comment?.fromEmployeeCode.toString(),comment?.videoComment.toString(),group?.comment?.commentCode,comment?.commentCode,video?.videoCoverPath, text, { commentId ->
                var comment = createLocalComment(commentId, text).apply {
                    toEmployeeCode = comment?.fromEmployeeCode
                    toEmployeeName = comment?.fromEmployeeName
                    lvlNo = if (comment == null) "2" else "3"
                }
                var num:Int= 0
                if(!Utils.isNull(group.comment.haveChild)){
                    num= group.comment.haveChild.toInt()
                }
                num++
                var numString:String=num.toString()
                group.comment.haveChild=numString
                group!!.children.add(0, comment)
                group.showChildren=true
                adapter.notifyDataSetChanged()
            }, {
                context.errorToast(it)
            })
        }
        dialog.show()
        if (comment != null) {
            dialog.editText?.hint = "回复 ${comment.fromEmployeeName}"
        } else {
            dialog.editText?.hint = "回复 ${group.comment.fromEmployeeName}"
        }
    }

    private fun createLocalComment(commentId:String, content:String):VideoComment {
        var comment = VideoComment()
        comment.commentCode = commentId
        comment.fromEmployeeName =  ShareUtils().getString(MyApp.appCtx, StaticClass.USER_NICKNAME, "")
        comment.fromEmployeeCode = ShareUtils().getString(MyApp.appCtx, StaticClass.EMPLOYEECODE, "")
        comment.videoComment = content
        comment.headPhotoThumbUrl = ShareUtils().getString(MyApp.appCtx, StaticClass.USER_AVATAR_URL, "")
        comment.createTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())
        comment.lvlNo ="1"
        comment.isLike ="0"
        comment.haveChild ="0"

        return comment
    }

    fun screenSizeInPixel(context: Context): Point {
        val dm = context.resources.displayMetrics
        val widthPixels = dm.widthPixels
        val heightPixels = dm.heightPixels
        return Point(Math.min(widthPixels, heightPixels), Math.max(widthPixels, heightPixels))
    }

    var pageSize = 20
    var isLoading = false
    var isEnd = false

    val viewModel = ViewModelProviders.of(context as FragmentActivity).get(VideoModel::class.java)
    val adapter by lazy {
        object: VideoCommentsAdapter() {
            override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup): View {
                if (groupPosition == groupCount - 1) {
                    loadMoreData()
                }
                return super.getGroupView(groupPosition, isExpanded, convertView, parent)
            }
        }
    }

    private fun loadMoreData() {
        if (isLoading || isEnd) {
            return
        }
        isLoading = true
        initFooter("加载中...", null)
        var pageNum = adapter.groupCount/pageSize
        getVideoComments(video.videoId, pageSize, pageNum, {
            if (pageNum == 0) {
                adapter.isLoadingGroupId = null
                adapter.groups.clear()
            }
            adapter.groups.addAll(it.map { VideoCommentsAdapter.GroupItem(it) })
            tvTitle.text = "${adapter.groups.size}条评论"
            adapter.notifyDataSetChanged()
            for (i in 0 until adapter.groupCount) {
                mListView.expandGroup(i)
            }
            isLoading = false
            if (it.size < pageSize) {
                isEnd = true
                if(adapter.groups.size==0){
                    initFooter("暂无评论", null)
                }else{
                    initFooter("已显示全部评论", null)
                }

            } else {
                initFooter("查看更多") { loadMoreData() }
            }
        }, {
            isLoading = false
            initFooter("加载出错,请点击重试") { loadMoreData() }
        })
    }

    private fun loadChildComments(group: VideoCommentsAdapter.GroupItem) {
        var pageSize = 10
        var pageNum = group.children.size/pageSize
        getVideoComments(group.comment.commentCode, pageSize, pageNum, {
            adapter.isLoadingGroupId = null
            group.children.addAll(it)
            adapter.notifyDataSetChanged()
        }, {
            adapter.isLoadingGroupId = null
            adapter.notifyDataSetChanged()
        })
    }

    private fun getVideoComments(code: String, pageSize: Int, pageNum: Int,
                                 _onSuccess: ((result: List<VideoComment>) -> Unit),
                                 _onError: ((error: String) -> Unit)) {
        val params2: MutableMap<String, Any?> = HashMap()
        params2["code"] = code
        params2["pageNum"] = (pageNum + 1).toString()
        params2["pageSize"] = pageSize.toString()

        httpForm<VideoCommentsListResponse> {
            url = "api/video/selectCommentByCode"
            params = params2
            onSuccess = {
                _onSuccess.invoke(it.data ?: emptyList())
            }
            onError = {
                _onError.invoke(it)
            }
        }
    }



    private fun initFooter(text: String, l: View.OnClickListener?) {
        footerView.tv.text = text
        if(text.equals("暂无评论")){
            footerView.noData.visibility = View.VISIBLE
        }else{
            footerView.noData.visibility = View.GONE
        }

        footerView.setOnClickListener(l)
    }
}

